import 'dart:convert';

import 'package:file_picker/file_picker.dart';
import 'package:flutter/cupertino.dart';
import 'package:flutter_easyloading/flutter_easyloading.dart';
import 'package:get/get.dart';
import 'package:mmkv/mmkv.dart';
import 'package:seedfour/app/models/user_info_entity.dart';
import 'package:seedfour/toolkit/utils/encrypt_utils.dart';

import '../../models/invoice_entity.dart';
import '../../routes/app_routes.dart';
import '../../services/api_service.dart';
import '../../services/common_service.dart';
import '../web_screen/screen_params.dart';

class WithdrawLogic extends GetxController {
  final mmkv = MMKV.defaultMMKV();
  final apiService = Get.find<ApiService>();
  final commonService = Get.find<CommonService>();

  var balance = '0.00'.obs;
  var bankInfo = UserInfoBank().obs;
  var rating = '0.00'.obs;
  var attachmentName = ''.obs;
  var isShowAttachment = false.obs;

  final isAllocOrder = false.obs;
  var allocOrderId = ''.obs;

  late GlobalKey<FormState> formKey;

  // 提现金额输入框控制器
  late TextEditingController amountController;

  // 银行名称输入框控制器
  late TextEditingController bankNameController;

  // 银行账户输入框控制器
  late TextEditingController bankAccountController;

  // 银行账户名输入框控制器
  late TextEditingController bankAccountNameController;

  // 备注输入框控制器
  late TextEditingController remarkController;

  // 支付密码输入框控制器
  late TextEditingController payPasswordController;

  late InvoiceEntity _invoiceEntity;

  String _payKey = '';

  var invoiceTotalAmount = '¥0.00'.obs;
  var attachmentNames = [].obs;
  final List<PlatformFile> _paths = [];

  @override
  void onInit() {
    super.onInit();

    formKey = GlobalKey<FormState>();
    amountController = TextEditingController();
    bankNameController = TextEditingController();
    bankAccountController = TextEditingController();
    bankAccountNameController = TextEditingController();
    remarkController = TextEditingController();
    payPasswordController = TextEditingController();
    _getUserAccountInfo();
    _invoiceEntity = InvoiceEntity();
    _invoiceEntity.orderAttachs = [];
    _invoiceEntity.invoiceList = [];
  }

  void initPasswordController() {
    payPasswordController = TextEditingController();
  }

  // 获取用户账户信息
  void _getUserAccountInfo() {
    WithdrawParams params = Get.arguments;

    isAllocOrder.value = params.isAllocOrder;
    allocOrderId.value = params.allocOrderId ?? '';

    apiService.getUserInfo(action: 'effect').then((user) {
      if (user != null) {
        if (Get.arguments != null) {
          // balance.value = Get.arguments;
          balance.value = params.balance;
        } else {
          balance.value = user.cashBalanceStr ?? '0.00';
        }
        rating.value = user.effect?.welfareEffect ?? '0.00';

        bankAccountNameController.text = user.bank?.withdrawName ?? '';
        bankAccountController.text = user.bank?.withdrawAcct ?? '';
        bankNameController.text = user.bank?.withdrawBank ?? '';
      }
    });
  }

  // 提交表单
  void submitWithdraw() {
    if (formKey.currentState!.validate()) {
      EasyLoading.show(status: '提交申请中...', dismissOnTap: true);

      _uploadFile();
    }
  }

  void toSelectInvoice() {
    String token = commonService.getToken() ?? '';
    String orgId = commonService.getUser().targetSite?.owner ?? '';
    String url =
        'https://www.seedfour.com/clicms/#/findata?orgId=$orgId&token=$token';
    Get.toNamed(RouteGet.webScreen, arguments: WebScreenParams(url: url))!
        .then((value) {
      if (value == null) {
        return;
      }

      printInfo(
          info: '------------------------------------------ 监听财务凭证H5页面返回数据事件');

      Map<String, dynamic> jsonMap = jsonDecode(value[0]);

      List<dynamic> invoiceListJson = jsonMap['invoiceList'];
      List<InvoiceItemEntity> invoiceList = invoiceListJson
          .map((json) => InvoiceItemEntity.fromJson(json))
          .toList();

      _invoiceEntity.invoiceList = invoiceList;

      print('invoiceList: ${_invoiceEntity.invoiceList.toString()}');

      invoiceTotalAmount.value = jsonMap['totalAmount'];
    });
  }

  void _withdraw() {
    _invoiceEntity.withdrawMode = 'bank';
    _invoiceEntity.withdrawName = bankAccountNameController.text;
    _invoiceEntity.withdrawAcct = bankAccountController.text;
    _invoiceEntity.withdrawBank = bankNameController.text;
    _invoiceEntity.orderRemark = remarkController.text;

    String password = rsaEncrypt(_payKey, payPasswordController.text);

    if (commonService.isAssistant()) {
      apiService
          .createAssistantPaidOrder(
              action: 'create',
              amount: amountController.text,
              invoice: _invoiceEntity.toString(),
              mobile: '',
              orderType: 3,
              title: '提现')
          .then((value) {
        if (value != null) {
          if (value.value['success'] == true) {
            EasyLoading.showSuccess('提现申请提交成功');
            Get.back(result: true);
          } else {
            EasyLoading.showError(value.value['error']['message']);
          }
        } else {
          EasyLoading.showError('提现申请提交失败');
        }
      });
    } else {
      //20250725 专款提现
      if(!isAllocOrder.value) {
        apiService.withdraw(
          amountController.text,
          _invoiceEntity.toString(),
          password,
              (e) {
            EasyLoading.showError(e.toString());
            return true;
          },
        ).then((value) {
          if (value != null) {
            if (value.value['success'] == true) {
              EasyLoading.showSuccess('提现成功');
              Get.back(result: true);
            } else {
              EasyLoading.showError(value.value['error']['message']);
            }
          } else {
            EasyLoading.showError('提现失败');
          }
        });
      }
      else{
        apiService.allocOrderWithdraw(
          allocOrderId.value,
          amountController.text,
          _invoiceEntity.toString(),
          password,
              (e) {
            EasyLoading.showError(e.toString());
            return true;
          },
        ).then((value) {
          if (value != null) {
            if (value.value['success'] == true) {
              EasyLoading.showSuccess('提现成功');
              Get.back(result: true);
            } else {
              EasyLoading.showError(value.value['error']['message']);
            }
          } else {
            EasyLoading.showError('提现失败');
          }
        });
      }
    }
  }

  void _getPayKey() {
    apiService.getPayKey(onError: (e) {
      EasyLoading.showError(e.toString());
      return true;
    }).then((value) {
      if (value != null && value.isNotEmpty) {
        _payKey = value;

        _withdraw();
      } else {
        EasyLoading.showError('请求失败');
      }
    });
  }

  void _uploadFile() {
    if (_paths.isEmpty) {
      _getPayKey();
      return;
    }

    for (var path in _paths) {
      apiService.uploadFile(path.path!, onError: (e) {
        EasyLoading.showError(e.toString());
        return true;
      }).then((value) {
        if (value != null) {
          _invoiceEntity.orderAttachs?.add(InvoiceOrderAttach(
            name: value.name,
            url: value.tempPath,
          ));
          _getPayKey();
        } else {
          EasyLoading.showError('文件上传失败');
        }
      });
    }

    // _getPayKey();
  }

  // 选择文件
  void pickFile() async {
    var files = (await FilePicker.platform.pickFiles(
      type: FileType.any,
      allowMultiple: true,
    ))
        ?.files;

    if (files != null && files.isNotEmpty) {
      _paths.addAll(files);
      attachmentNames.addAll(files.map((e) => e.name).toList());
    }
  }

  // 删除文件
  void deleteFile(int index) {
    _paths.removeAt(index);
    attachmentNames.removeAt(index);
  }

  @override
  void onClose() {
    amountController.dispose();
    bankNameController.dispose();
    bankAccountController.dispose();
    bankAccountNameController.dispose();
    remarkController.dispose();
    super.onClose();
  }
}
class WithdrawParams {
  String balance;
  bool isAllocOrder = false;
  String? allocOrderId;

  WithdrawParams({  required this.balance, this.allocOrderId = '', this.isAllocOrder = false});
}